package com.seafwg.mall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seafwg.common.utils.PageUtils;
import com.seafwg.common.utils.Query;

import com.seafwg.mall.product.dao.CategoryDao;
import com.seafwg.mall.product.entity.CategoryEntity;
import com.seafwg.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询所有分类包括子分类
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查询出所有的分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2.组装数据结构
        // 2.1 找到所有一级分类
        List<CategoryEntity> leveMenus = entities.stream().filter(
            item -> item.getParentCid() == 0
        ).map(
            item -> {
                item.setChildren(getChildren(item, entities));
                return item;
            }
        ).sorted(
            (item1, item2) -> (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort())
        ).collect(Collectors.toList());
        return entities;
    }

    // 递归获取所有的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> entities) {

        List<CategoryEntity> children = entities.stream().filter(
            item -> item.getParentCid().equals(root.getCatId())
        ).map(
            item -> {
                item.setChildren(getChildren(item, entities));
                return item;
            }
        ).sorted(
            (item1, item2) -> (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort())
        ).collect(Collectors.toList());

        return children;
    }

}